<template>
	<view class="loginPage">
		<!-- 背景装饰 -->
		<view class="bg-decoration"></view>

		<!-- 头部欢迎语 -->
		<view class="welcome-box">
			<image class="welcome-bg" src="/static/images/use_bg2.png" mode="aspectFit" />
		</view>

		<!-- Tab切换 -->
		<view class="tab-box">
			<view class="tab-item" :class="{ active: loginType === 'code' }" @click="switchLoginType('code')">
				验证码登录
			</view>
			<!-- <view class="tab-item" :class="{ active: loginType === 'password' }" @click="switchLoginType('password')">
				密码登录
			</view> -->
		</view>

		<!-- 表单区域 -->
		<view class="form-box">
			<!-- 手机号输入 -->
			<view class="input-item">
				<image class="input-icon" src="/static/images/ic_phone.png" mode="aspectFit"></image>
				<input class="input-field" type="number" maxlength="11" v-model="mobile" placeholder="请输入手机号"
					placeholder-class="placeholder-style" />
			</view>

			<!-- 验证码登录 -->
			<view class="input-item" v-if="loginType === 'code'">
				<image class="input-icon" src="/static/images/ic_check.png" mode="aspectFit"></image>
				<input class="input-field" type="number" maxlength="6" v-model="code" placeholder="请输入验证码"
					placeholder-class="placeholder-style" />
				<view class="code-btn" @click="sendCode">
					<text :class="{ disabled: countdown > 0 }">
						{{ countdown > 0 ? `${countdown}s` : '获取验证码' }}
					</text>
				</view>
			</view>

			<!-- 密码登录 -->
			<!-- <view class="input-item" v-if="loginType === 'password'">
				<image class="input-icon" src="/static/images/ic_pwd.png" mode="aspectFit"></image>
				<input class="input-field" :type="showPassword ? 'text' : 'password'" v-model="password"
					placeholder="请输入密码" placeholder-class="placeholder-style" />
				<u-icon :name="showPassword ? 'eye' : 'eye-off'" size="40rpx" color="#999"
					@click="showPassword = !showPassword"></u-icon>
			</view> -->

			<!-- 新用户注册/忘记密码 -->
			<!-- <view class="link-box">
				<text class="link-text" @click="toRegister">新用户注册</text>
				<text class="link-text_f" v-if="loginType === 'password'" @click="toForgetPassword">忘记密码</text>
			</view> -->

			<!-- 登录按钮 -->
			<view class="login-btn" @click="handleLogin">
				<text class="login-btn-text">登录</text>
			</view>
		</view>

		<!-- 协议勾选 -->
		<view class="agreement-box">
			<u-checkbox-group v-model="isread" @change="checkboxChange">
				<view class="check">
					<u-checkbox name="read" shape="circle" />
					<text class="text">我已阅读并同意</text>
					<text class="text xieyiColor" @click="toUserAgreement('OX_MAN_USER_PROTOCOL')">
						《用户协议》
					</text>
					<text class="text">和</text>
					<text class="text xieyiColor" @click="toUserAgreement('OX_MAN_PRIVACY_AGREEMENT')">
						《隐私政策》
					</text>
				</view>
			</u-checkbox-group>
		</view>
	</view>
</template>

<script>
	import {
		getCustomerInfoByToken,
		login,
		loginSalesmanTokenByPhoneWithToken
	} from "@/api/login.js";
	import {
		sendMsm,
		phoneCodeLogin
	} from "@/api/userSalesman.js";
	import {
		appIdCard
	} from "@/api/card";
	import {
		getOpenId
	} from "@/api/userSalesman.js";
	import {
		mapGetters
	} from "vuex";

	export default {
		data() {
			return {
				loginType: 'code', // 'code' 验证码登录, 'password' 密码登录
				mobile: '',
				code: '',
				// password: '',
				// showPassword: false,
				countdown: 0,
				timer: null,
				isread: [],
			};
		},
		computed: {
			...mapGetters(["inviteLogin"]),
		},
		onUnload() {
			if (this.timer) {
				clearInterval(this.timer);
			}
		},
		methods: {
			// 切换登录方式
			switchLoginType(type) {
				this.loginType = type;
				// 清空输入
				this.code = '';
				// this.password = '';
			},

			// 发送验证码
			async sendCode() {
				if (this.countdown > 0) return;

				if (!this.mobile) {
					return uni.$u.toast('请输入手机号');
				}

				if (!/^1[3-9]\d{9}$/.test(this.mobile)) {
					return uni.$u.toast('请输入正确的手机号');
				}

				try {
					// 调用发送验证码接口
					const result = await sendMsm(this.mobile);

					if (result.code === 200) {
						uni.$u.toast('验证码已发送');

						// 开始倒计时
						this.countdown = 60;
						this.timer = setInterval(() => {
							this.countdown--;
							if (this.countdown <= 0) {
								clearInterval(this.timer);
							}
						}, 1000);
					} else {
						uni.$u.toast(result.msg || '发送失败');
					}
				} catch (error) {
					uni.$u.toast(error.msg || '发送失败');
				}
			},

			// 勾选协议
			checkboxChange(n) {
				// 可以添加隐私协议弹窗逻辑
			},

			// 跳转用户协议
			toUserAgreement(code) {
				uni.navigateTo({
					url: "/pages/agreement/userAgreement/index?code=" + code
				});
			},

			// 跳转注册
			// toRegister() {
			// 	uni.navigateTo({
			// 		url: "/pages/user/phone/register"
			// 	});
			// },

			// 跳转忘记密码
			// toForgetPassword() {
			// 	uni.navigateTo({
			// 		url: "/pages/user/phone/forget"
			// 	});
			// },

			// 登录处理
			async handleLogin() {
				// 验证协议
				if (!this.isread.length) {
					return uni.$u.toast('请阅读并勾选协议');
				}

				// 验证手机号
				if (!this.mobile) {
					return uni.$u.toast('请输入手机号');
				}

				if (!/^1[3-9]\d{9}$/.test(this.mobile)) {
					return uni.$u.toast('请输入正确的手机号');
				}

				// 验证码登录验证
				if (this.loginType === 'code') {
					if (!this.code) {
						return uni.$u.toast('请输入验证码');
					}
					if (this.code.length  > 6) {
						return uni.$u.toast('请输入小于6位验证码');
					}
					await this.loginWithCode();
				}
				// 密码登录验证
				// else {
				// 	if (!this.password) {
				// 		return uni.$u.toast('请输入密码');
				// 	}
				// 	if (this.password.length < 6) {
				// 		return uni.$u.toast('密码长度不能少于6位');
				// 	}
				// 	await this.loginWithPassword();
				// }
			},

			// 验证码登录
			async loginWithCode() {
				try {
					uni.showLoading({
						title: '登录中...'
					});

					// 调用验证码登录接口
					const params = {
						phone: this.mobile,
						validationCode: this.code
					};
					const result = await phoneCodeLogin(params);

					if (result.code === 200) {
						// 登录成功后，调用获取业务员token的接口
						await this.handleLoginSuccess(result.data.access_token);
					} else {
						uni.$u.toast(result.msg || '登录失败');
					}

				} catch (error) {
					uni.$u.toast(error.msg || '登录失败');
				} finally {
					uni.hideLoading();
				}
			},

			// 密码登录
			// async loginWithPassword() {
			// 	try {
			// 		uni.showLoading({
			// 			title: '登录中...'
			// 		});

			// 		// TODO: 调用密码登录接口
			// 		// const params = {
			// 		// 	mobile: this.mobile,
			// 		// 	password: this.password
			// 		// };
			// 		// const result = await loginWithPasswordApi(params);

			// 		// 暂时禁用密码登录，提示用户使用验证码登录
			// 		uni.$u.toast('密码登录功能暂未实现，请使用验证码登录');
			// 		uni.hideLoading();

			// 	} catch (error) {
			// 		uni.$u.toast(error.msg || '登录失败');
			// 	} finally {
			// 		uni.hideLoading();
			// 	}
			// },

			// 登录成功后的统一处理（和小程序登录页面逻辑一致）
			async handleLoginSuccess(access_token) {
				const that = this;
				// 先设置客户端token
				if (access_token) {
					await that.$store.commit("SET_TOKEN", access_token);
					await that.$store.commit("SET_TOKEN_CUSTOMER", access_token);
				}

				// 调用获取业务员token的接口（和小程序登录保持一致）
				await loginSalesmanTokenByPhoneWithToken().then(async (result) => {
					// 是业务员 直接返回业务员token 再覆盖一遍登录的时候客户的token
					if (result.data.access_token) {
						await that.$store.commit("SET_TOKEN", result.data.access_token);
						// 设置权限为业务员
						that.$store.commit("SET_AUTHORITY", "salesman");
					} else {
						// 设置权限为客户
						that.$store.commit("SET_AUTHORITY", "customer");
					}
				}).catch(error => {
					// 即使获取业务员token失败，也继续执行
					that.$store.commit("SET_AUTHORITY", "customer");
				});

				// 获取用户信息
				await that.$store.dispatch("USERINFO", {
					$u: uni.$u
				});

				// 获取跳转地址
				let url = "/pages/counselling/index";
				const loginBackUrl = uni.getStorageSync("loginBackUrl");
				if (loginBackUrl) url = loginBackUrl;
				const loginBackUrlOption = uni.getStorageSync("loginBackUrlOption") || {};

				// 跳转页面
				if (url === "/pages/counselling/index") {
					that.$store.commit("SET_CURRENT_TAB_INDEX", 0);
					uni.reLaunch({
						url: this.inviteLogin.name ?
							`/pages_activity/invitation/inviteMembers?name=${this.inviteLogin.name}&mobile=${this.inviteLogin.mobile}&avatar=${this.inviteLogin.avatar}` :
							"/pages/counselling/index",
					});
				} else {
					uni.$u.route({
						type: "reLaunch",
						url,
						params: loginBackUrlOption
					});
				}
			},

			// 登录成功后的处理（保留原有方法作为备用）
			async loginSuccess() {
				const that = this;

				// 获取用户信息
				await that.$store.dispatch("USERINFO", {
					$u: uni.$u
				});

				// 获取跳转地址
				let url = "/pages/counselling/index";
				const loginBackUrl = uni.getStorageSync("loginBackUrl");
				if (loginBackUrl) url = loginBackUrl;
				const loginBackUrlOption = uni.getStorageSync("loginBackUrlOption") || {};

				// 跳转页面
				if (url === "/pages/counselling/index") {
					that.$store.commit("SET_CURRENT_TAB_INDEX", 0);
					uni.reLaunch({
						url: this.inviteLogin.name ?
							`/pages_activity/invitation/inviteMembers?name=${this.inviteLogin.name}&mobile=${this.inviteLogin.mobile}&avatar=${this.inviteLogin.avatar}` :
							"/pages/counselling/index",
					});
				} else {
					uni.$u.route({
						type: "reLaunch",
						url,
						params: loginBackUrlOption
					});
				}
			}
		}
	};
</script>

<style lang="scss" scoped>
	.loginPage {
		width: 100vw;
		min-height: 100vh;
		background-image: url('/static/images/use_bg.png');
		background-size: cover;
		background-repeat: no-repeat;
		background-position: center;
		position: relative;
		padding: 0 46rpx;
		box-sizing: border-box;
	}

	.bg-decoration {
		position: absolute;
		top: 0;
		right: 0;
		width: 100%;
		height: 400rpx;
		background-image: radial-gradient(circle at top right, rgba(88, 139, 243, 0.15) 0%, transparent 60%);
		pointer-events: none;
	}

	.welcome-box {
		padding-top: 120rpx;
		margin-bottom: 48rpx;
		width: 100%;
		display: flex;

		.welcome-bg {
			width: 340rpx;
			height: 124rpx;
		}
	}

	.tab-box {
		display: flex;
		margin-bottom: 60rpx;

		.tab-item {
			font-size: 32rpx;
			color: #999999;
			margin-right: 60rpx;
			padding-bottom: 16rpx;
			position: relative;

			&.active {
				color: #3D3D3D;
				font-weight: 600;

				&::after {
					content: '';
					position: absolute;
					bottom: 0;
					left: 0;
					width: 100%;
					height: 6rpx;
					background: #588BF3;
					border-radius: 3rpx;
				}
			}
		}
	}

	.form-box {
		.input-item {
			display: flex;
			align-items: center;
			height: 100rpx;
			background: rgba(255, 255, 255, 0.8);
			border-radius: 50rpx;
			padding: 0 40rpx;
			margin-bottom: 32rpx;

			.input-icon {
				width: 40rpx;
				height: 40rpx;
				flex-shrink: 0;
			}

			.input-field {
				flex: 1;
				font-size: 28rpx;
				color: #3D3D3D;
				margin-left: 24rpx;
			}

			.placeholder-style {
				color: #CCCCCC;
			}

			.code-btn {
				padding-left: 20rpx;
				border-left: 1rpx solid #EAEAEA;

				text {
					font-size: 26rpx;
					color: #588BF3;

					&.disabled {
						color: #CCCCCC;
					}
				}
			}
		}

		.link-box {
			display: flex;
			justify-content: space-between;
			margin-bottom: 60rpx;

			.link-text {
				font-size: 28rpx;
				color: #588BF3;
			}

			.link-text_f {
				font-size: 28rpx;
				color: #777777;
			}
		}

		.login-btn {
			height: 100rpx;
			background: linear-gradient(90deg, #6B9EFF 0%, #588BF3 100%);
			border-radius: 50rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			box-shadow: 0 8rpx 24rpx rgba(88, 139, 243, 0.3);

			.login-btn-text {
				font-size: 36rpx;
				color: #FFFFFF;
				font-weight: 600;
			}
		}
	}

	.agreement-box {
		margin-top: 300rpx;
		width: 100%;

		.check {
			display: flex;
			justify-content: center;
			align-items: center;

			.text {
				font-size: 28rpx;
				color: #666666;
			}

			.xieyiColor {
				color: #588BF3 !important;
			}
		}
	}
</style>